# 使用阿里云OSS + picGo搭建图床 参考 https://www.jianshu.com/p/111ce9603ea6l
import time
# -*- coding: utf-8 -*-
import datetime
import oss2
import unittest
from pathlib import Path

#参考 https://www.likecs.com/show-308529932.html#sc=900
class OSS:
    """
    oss存储类
    上传bytes流，返回状态码和url
    """
    def __init__(self, access_key_id="", access_key_secret="",
                 endpoint="", bucket_name=""):
        '''
        @param access_key_id : RAM账号access_key_id,如果没有用主账号登录工作台创建并授权
        @param access_key_secret : RAM账号access_key_secret
        @param endpoint : 在bucket中获取地域节点endpoint
        @param bucket_name : bucket名称
        '''
        # 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        auth = oss2.Auth(access_key_id, access_key_secret)
        # Endpoint以杭州为例，其它Region请按实际情况填写。'http://oss-cn-hangzhou.aliyuncs.com'
        self.bucket = oss2.Bucket(auth, endpoint, bucket_name)
        self.domain = f'https://{bucket_name}.{endpoint}/'

    def upload_bytes(self, file_bytes, image_name):
        """上传bytes文件,返回(上传结果，图片链接）"""
        result = self.bucket.put_object('{}'.format(image_name), file_bytes)
        url = self.domain + image_name
        return result, url

    def upload_files(self,picPaths_dict):
        '''
        @param picPaths_dict 要上传图片的本地文件路径; type=list
        @return pic_urls_dict 上传到OSS上得到的图片url链接; type=list
        '''
        pic_urls_dict = {}
        for key in picPaths_dict.keys():
            picPath = picPaths_dict[key]
            file_bytes = open(picPath,"rb")
            file_name_tokens = Path(picPath).name.split(".")

            timestramp = time.time()
            file_name_temp = file_name_tokens[0] + "_" + str(timestramp) + file_name_tokens[1]
            result,url = self.upload_bytes(file_bytes,file_name_temp)
            if(result): #上传成功
                pic_urls_dict[key] = url
        return pic_urls_dict